using System.Reflection;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using PowerManage.EntityFrameworkCore;
using PowerManage.Entity;

var builder = WebApplication.CreateBuilder(args);

//数据库上下文注入
builder.Services.AddDbContext<ApplicationDbContext>(options => {
    //启用的数据库类型
    var provider = builder.Configuration.GetValue<string>("DataProvider");
    switch (provider) {
        case "PgSql":
            var pgSqlConnectionString = builder.Configuration.GetConnectionString("PgSqlConnection") ??
                                        throw new InvalidOperationException(
                                            "PgSqlConnection在appsettings.json中 not found");
            options.UseNpgsql(pgSqlConnectionString,  b => b.MigrationsAssembly("PowerManage.DbMigrator"));
            break;
        case "Mysql":
            var mySqlConnectionString = builder.Configuration.GetConnectionString("MysqlConnection") ??
                                        throw new InvalidOperationException(
                                            "MysqlConnection在appsettings.json中 not found");
            //MySql需要传入版本，ServerVersion.AutoDetect根据连接字符串自动获取
            options.UseMySql(mySqlConnectionString, ServerVersion.AutoDetect(mySqlConnectionString),  b => b.MigrationsAssembly(Assembly.GetExecutingAssembly().FullName));
            break;
    }
});

//Identity注入，添加数据库上下文 配置认证，授权 里面存储用户和角色数据  AddDefaultTokenProviders()：添加默认的令牌提供者
// builder.Services.AddIdentity<IdentityUser, IdentityRole>()
//     .AddEntityFrameworkStores<ApplicationDbContext>().AddDefaultTokenProviders();
//这里是为了自定义Identity表名称 功能和上述注释的一样
builder.Services.AddIdentity<EleUser, EleRole>()
    .AddEntityFrameworkStores<ApplicationDbContext>().AddDefaultTokenProviders();

// Add services to the container.

builder.Services.AddControllers();

var app = builder.Build();

// Configure the HTTP request pipeline.

app.UseAuthorization();

app.MapControllers();

app.Run();